package com.husd.framework.compile;

import com.sun.javadoc.*;

/**
 * @author shengdonghu@126.com
 * @date 2022/8/23 14:08
 */
public class ParserByJavaDoc extends Doclet {
    private static RootDoc rootDoc;

    private String sourceFile;

    public static class Doclet {
        private Doclet() {
        }

        @SuppressWarnings("all")
        public static boolean start(RootDoc rootDoc) {
            ParserByJavaDoc.rootDoc = rootDoc;
            return true;
        }

        // 返回Java1.5 因为泛型是在Java1.5后加入的特性，获取变量类型时要获取泛型就需要重写此方法
        @SuppressWarnings("all")
        public static LanguageVersion languageVersion() {
            return LanguageVersion.JAVA_1_5;
        }
    }

    public ParserByJavaDoc(String sourceFile) {

        String[] params = new String[]{"-doclet",
                Doclet.class.getName(),
                "-encoding", "utf-8", "-quiet", sourceFile};
        this.sourceFile = sourceFile;
        com.sun.tools.javadoc.Main.execute(params);
    }

    public ClassDoc getClassDoc() {

        ClassDoc[] classes = rootDoc.classes();
        if(classes == null || classes.length == 0) {
            System.out.println("------------- error source file is : " + this.sourceFile);
            return null;
        }
        ClassDoc classDoc = classes[0];
        return classDoc;
    }

    private static void parse() {
        ClassDoc[] classes = rootDoc.classes();
        ClassDoc classDoc = classes[0];
        System.out.println("Find Class Definition");
        System.out.println(classDoc.getRawCommentText());
        System.out.println(classDoc.qualifiedName());
        System.out.println("Find Imports");
        for (PackageDoc packageDoc : classDoc.importedPackages()) {
            System.out.println(packageDoc.name());
        }
        System.out.println("Find Field Definition");
        for (FieldDoc fieldDoc : classDoc.fields(false)) {
            System.out.println(fieldDoc.getRawCommentText());
            System.out.println(fieldDoc.type());
            System.out.println(fieldDoc.name());
        }
    }

}